package ir;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class FieldNode extends MemberNode {

  private Class<?> c;

  private String fieldname;
  
  
  public FieldNode(Class<?> c, String fieldname) {
    this.c  = c;
    this.fieldname = fieldname;
  }
  
  public String getName() {
    return fieldname;
  }
  
  /**
   * Is this field's data type qualified for mapping into a GWT data type?
   * @return
   */
  public boolean isTypeQualified() {
    
    // check the component type if we're dealing with an array
    Class<?> type;
    if (c.isArray())
      type = c.getComponentType();
    else type = c;
    
    return (! type.isPrimitive() && ! type.equals(String.class) 
        && ! type.getCanonicalName().contains("java.lang") && ! type.getCanonicalName().contains("java.util"));
  }
  
  /**
   * Code generation function; should produce a line of Java code representing
   * the field. E.g. "private String name;"
   * @return the line of code corresponding to this field.
   */
  @Override
  public String gen() {
//    return "F " + Modifier.toString(f.getModifiers()) +
//      " " + f.getType().getSimpleName() + 
//      " " + f.getName() + "\n";
    return  INDENT + "private " + gwtifyName(c) + " "+ fieldname + ";\n";
  }
  
  public String getTypeName() {
    return gwtifyName(c);
  }

  public String genGwt2Soap() {
    String inget = "in.get" + getName() + "()";
    String checker = "(in == null) ? null :" + inget;
    if (isTypeQualified())
      return "if (in != null) out.set" + getName() + "( Translator.instance().Gwt2Soap(" + inget +"));\n";
    else
      return "if (in != null) out.set" + getName() + "(" + inget + ");\n";
  }

  public String genSoap2Gwt() {
    String inget = "in.get" + getName() + "()";
    String checker = "(in == null) ? null :" + inget;
    if (isTypeQualified())
      return "if (in != null) out.set" + getName() + "( Translator.instance().Soap2Gwt(" + inget + "));\n";
    else
      return "if (in != null) out.set" + getName() + "(" + inget +" );\n";
  }

}
